package com.meusconcursos.dataupdate;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.meusconcursos.MeusConcursosActivity;

public abstract class Table {

	public Table() {
		super();
		getDb().execSQL(getScriptTableDelete());

		try {
			getDb().execSQL(getScriptTableCreate());
		} catch (SQLException e) {
			Log.e(MeusConcursosActivity.DEBUG_TAG, "Falhou criando tabela ["
					+ getTableName() + "] a partir do script ["
					+ getScriptTableCreate() + "].");
		}
	}

	private List<Record> records = null;

	public boolean add(Record record) {
		if (records == null) {
			records = new ArrayList<Record>();
		}
		return records.add(record);
	}

	public static final String SCRIPT_TABLE_DELETE = "DROP TABLE IF EXISTS ";

	public String getScriptTableDelete() {
		return SCRIPT_TABLE_DELETE + getTableName();
	}

	public abstract String getTableName();

	public String getHeaderScriptTableCreate() {
		return "CREATE TABLE " + getTableName() + " ";
	}

	public abstract String getScriptTableCreate();

	SQLiteDatabase getDb() {
		return MeusConcursosActivity.dbHelper.getWritableDatabase();
	}

	public long inserir(ContentValues cv) {
		long id = getDb().insert(getTableName(), null, cv);

		if (id < 0) {
			Log.e(MeusConcursosActivity.DEBUG_TAG,
					"Falhou inserindo registro em " + getTableName() + " ["
							+ cv.toString() + "]");
		}

		return id;
	}

	public long atualizar(ContentValues cv) {
		long rows = getDb().update(getTableName(), cv, "_id = ?",
				new String[] { String.valueOf(cv.getAsString("_id")) });
		return rows;
	}

	public List<Record> getRecords() {
		return records;
	}

	public void setRecords(List<Record> records) {
		this.records = records;
	}

	public int excluir(int id) {
		int rows = getDb().delete(getTableName(), "_id = ?",
				new String[] { String.valueOf(id) });
		return rows;
	}

	public abstract Record newRecordInstance(String[] values);

}
